<template>
	<view class="container">
		<view class="top">
			<!-- 地图卡片 -->
			<uni-card margin="15rpx" class="map-card">
				<view :style="{ height: showStoreInfo ? '780rpx' : '100vh' }" class="map-container">
					<!-- 添加 @callouttap 事件监听 -->
					<map @markertap="mkp" @callouttap="handleCalloutTap" scale="15" :markers="mks" :longitude="longitude" :latitude="latitude"
						class="map"></map>
				</view>
			</uni-card>
		</view>

		<!-- 门店信息卡片，初始隐藏 -->
		<view v-if="showStoreInfo" style=" margin-top: 600rpx; padding: 15rpx;">
			<view class="store-title">
				{{ selectedInfo?.name || '' }}
			</view>
			<view class="store-rating">
				<uni-rate :value="selectedInfo?.rate || 4" max="5" size="28" color="#ffb400" readonly
					allow-half="false" />
				<text class="score">{{ selectedInfo?.rate || 4 }}分</text>
				<text class="distance">{{ jl }} m</text>
			</view>
			<view class="store-detail-row">
				<view class="store-detail-col">
					<view>营业时间：{{ selectedInfo?.startTime }} - {{ selectedInfo?.endTime }}</view>
					<view>位置：{{ selectedInfo?.address }}</view>
				</view>
				<!-- 使用计算属性获取图片路径 -->
				<image class="store-img" :src="selectedImage" mode="aspectFill" />

			</view>
			<!-- 底部按钮 -->
			<view class="bottom-btns">
				<button class="contact-btn" @click="contactShop">
					<image class="btn-icon" src="/static/autoRepair/phone.png" />
					联系门店
				</button>
				<button class="reserve-btn" @click="goToParticuars">
					<image class="btn-icon" src="/static/autoRepair/reserve.png" />
					立即预约
				</button>
			</view>
		</view>
		<!-- 自定义弹窗 -->
		<uni-popup ref="popupRef" type="bottom">
			<view class="popup-content">
				<view class="popup-phone" @click="callPhone">{{ phone }}</view>
				<button class="popup-btn" @click="copyPhone">复制</button>
				<button class="popup-btn cancel" @click="closePopup">取消</button>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import {
	ref,
	computed
} from 'vue';
import {
	onLoad
} from '@dcloudio/uni-app'
import request from '@/untils/request.js'
import baseUrl from '@/untils/urlConfig.js'


// 控制商家信息是否显示
const showStoreInfo = ref(false);

// 商家信息列表
const infoList = ref([]);
//照片列表
const imageList = ref([]);
// 当前选中的商家信息
const selectedInfo = ref(null);

// 地图标记
const mks = ref([]);
// 计算距离
const jl = ref(0)

// 经纬度
const latitude = ref(30.826128)
const longitude = ref(110.558902)

// 初始化自身位置标记
mks.value = [{
	id: 999,
	latitude: latitude.value,
	longitude: longitude.value,
	width: 20,
	height: 20,
	iconPath: '/static/dw1.png',
	callout: {
		content: "附近门店>",
		color: "#fff",
		bgColor: '#fe6430',
		borderRadius: 10,
		padding: 10,
		display: "ALWAYS",
	}
}]

// 获取当前坐标信息
function getLocation() {
	uni.getLocation({
		success(res) {
			latitude.value = res.latitude;
			longitude.value = res.longitude;

			const selfMarker = mks.value.find(marker => marker.id === 999);
			if (selfMarker) {
				selfMarker.latitude = latitude.value;
				selfMarker.longitude = longitude.value;
			}
		}
	})
}

// 选择商家的函数
function mkp(e) {
	const markerId = e.detail.markerId;
	if (markerId === 999) {
		uni.navigateTo({ url: '/pages/fujinmendian/fujinmendian' });
		return;
	}
	selectedInfo.value = infoList.value.find(obj => obj.id === markerId);
	if (selectedInfo.value) {
		// 计算距离
		let lat1 = latitude.value
		let lon1 = longitude.value;
		let lat2 = e.detail.latitude;
		let lon2 = e.detail.longitude;
		let distance = calculateDistanceInMeters(lat1, lon1, lat2, lon2);
		jl.value = distance.toFixed(2);
		// 显示商家信息
		showStoreInfo.value = true;
	}
}

// 当页面加载后立马执行
onLoad(() => {
	getLocation()
	// 使用request请求数据
	request({
		url: baseUrl + '/chy/merchant/list',
		method: 'GET',
		success: (res) => {
			if (res.data.code === 200) {
				res.data.rows.forEach(item => {
					mks.value.push({
						id: item.id,
						latitude: item.latitude,
						longitude: item.longitude,
						width: 20,
						height: 20,
						iconPath: item.iconPath || '/static/dw1.png',
						title: item.name,
					});
					infoList.value.push({
						id: item.id,
						name: item.name,
						rate: item.rate,
						// 截取 startTime 后八位
						startTime: item.startTime.slice(-8),
						// 截取 endTime 后八位
						endTime: item.endTime.slice(-8),
						address: item.address,
					});
				});
			}
		}
	});
	request({
		url: baseUrl + '/chy/tupian/list',
		method: 'GET',
		success: (r) => {
			if (r.data.code === 200) {
				r.data.rows.forEach(item => {
					imageList.value.push({
						id: item.id,
						mid: item.mid,
						image: item.img,
					});
				});
			}
		}
	});
	console.log(infoList.value);
});

function calculateDistanceInMeters(lat1, lon1, lat2, lon2) {
	const R = 6371000;
	const dLat = degToRad(lat2 - lat1);
	const dLon = degToRad(lon2 - lon1);
	const a =
		Math.sin(dLat / 2) * Math.sin(dLat / 2) +
		Math.cos(degToRad(lat1)) * Math.cos(degToRad(lat2)) *
		Math.sin(dLon / 2) * Math.sin(dLon / 2);
	const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
	return R * c;
}

// 辅助函数：将角度转换为弧度
function degToRad(deg) {
	return deg * (Math.PI / 180);
}

// 定义一个函数，选择地理位置
function chose() {
	// #ifdef H5
	navigator.geolocation.getCurrentPosition(
		position => {
			// 处理获取到的位置信息
		},
		error => {
			// 处理错误
		}
	);
	// #endif
	// #ifndef H5
	uni.chooseLocation({
		success(res) {
			// 处理选择后的位置
		}
	})
	// #endif
}

// 菜单点击事件
function change(e) {
	if (e.detail.index === 0) {
		uni.navigateTo({ url: '/pages/autoRepair/autoRepair' })
	}
}

const phone = '18642589456';
const popupRef = ref(null);

function contactShop() {
	popupRef.value.open();
}
function closePopup() {
	popupRef.value.close();
}
function copyPhone() {
	uni.setClipboardData({
		data: phone,
		success: function () {
			uni.showToast({ title: '已复制', icon: 'none' });
			closePopup();
		}
	});
}

function callPhone() {
	uni.makePhoneCall({ phoneNumber: phone });
}

function goToParticuars() {
    // 找出当前选中店铺对应的图片信息
    const selectedImageInfo = imageList.value.find(item => item.mid === selectedInfo.value?.id);
    const selectedImage = selectedImageInfo ? selectedImageInfo.image : '';

    // 仅传递当前显示的数据
    uni.navigateTo({
		url: `/pages/autoRepair/particulars/particulars?selectedInfo=${encodeURIComponent(JSON.stringify(selectedInfo.value))}&selectedImage=${JSON.stringify(encodeURIComponent(selectedImage))}`
    });
}

// Define a computed property to get the image path of the currently selected merchant
const selectedImage = computed(() => {
	if (!selectedInfo.value) return '';
	const matchImage = imageList.value.find(item => item.mid === selectedInfo.value.id);
	return matchImage ? matchImage.image : '';
});

// 定义处理 callout 点击的函数
function handleCalloutTap(e) {
	const markerId = e.detail.markerId;
	if (markerId === 999) {
		// 跳转到指定页面
		uni.navigateTo({ url: '/pages/fujinmendian/fujinmendian' });
	}
}
</script>

<style>
.container {
	background: #fff;
	min-height: 100vh;
	padding-bottom: 80rpx;
}

.top {
	margin-top: -15rpx;
	padding-top: 20rpx;
	height: 300rpx;
	background-color: #3083fb;
}

.map-container {
	position: relative;
	border-radius: 20rpx;
	overflow: hidden;
}

.map {
	width: 100%;
	height: 100%;
}

.map-btn {
	position: absolute;
	top: 20rpx;
	left: 50%;
	transform: translateX(-50%);
	background: #ff7f2a;
	color: #fff;
	padding: 8rpx 24rpx;
	border-radius: 30rpx;
	font-size: 24rpx;
	z-index: 2;
}

.info-section {
	background: #fff;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 8rpx #eee;
	padding: 24rpx;
}

.store-title {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 12rpx;
}

.store-rating {
	display: flex;
	align-items: center;
	margin-bottom: 12rpx;
}

.star {
	color: #ffb400;
	font-size: 28rpx;
	margin-right: 12rpx;
}

.score {
	color: #666;
	font-size: 24rpx;
	margin-right: 12rpx;
}

.distance {
	color: #1e90ff;
	font-size: 24rpx;
	margin-left: auto;
}

.store-detail {
	color: #888;
	font-size: 24rpx;
	margin-bottom: 12rpx;
}

.store-img {
	width: 180rpx;
	height: 120rpx;
	border-radius: 12rpx;
	margin-left: 24rpx;
	object-fit: cover;
}

/* 修改商家信息框的内边距 */
.store-detail-col {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
	padding: 10rpx;
	/* 减少内边距 */
}

/* 给商家信息框设置最大高度 */
.store-detail-row {
	display: flex;
	align-items: center;
	margin-bottom: 12rpx;
	max-height: 200rpx;
	/* 设置最大高度 */
	overflow: auto;
	/* 当内容超出高度时显示滚动条 */
}

/* 调整门店信息卡片整体的内边距 */
.view[v-if="showStoreInfo"] {
	padding: 15rpx;
	/* 减少内边距 */
}

.bottom-btns {
	width: 100%;
	margin-top: 40rpx;
	display: flex;
	background: #fff;
}

.contact-btn {
	flex: 1;
	margin: 0 16rpx 0 32rpx;
	background: #1677ff;
	color: #fff;
	border-radius: 40rpx;
	font-size: 32rpx;
}

.reserve-btn {
	flex: 1;
	margin: 0 32rpx 0 16rpx;
	background: #ff7f2a;
	color: #fff;
	border-radius: 40rpx;
	font-size: 32rpx;
}

.map-card {
	border-radius: 20rpx !important;
	overflow: hidden;
}

.btn-icon {
	width: 32rpx;
	height: 32rpx;
	margin-right: 12rpx;
	vertical-align: middle;
}

.popup-content {
	padding: 32rpx 0 16rpx 0;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
	text-align: center;
}

.popup-phone {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 32rpx;
}

.popup-btn {
	width: 100%;
	border: none;
	background: #fff;
	font-size: 32rpx;
	padding: 24rpx 0;
	border-top: 1px solid #eee;
}

.popup-btn.cancel {
	color: #888;
}
</style>
